package youleche.com.controler.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;

import youleche.com.business.BRentVehicleInfo;
import youleche.com.business.BUser;
import youleche.com.business.BVehicleInfo;
import youleche.com.common.ParamConfigParameters;
import youleche.com.controler.servlet.common.UlecheHttpServlet;
import youleche.com.factory.MLLogFactory;
import youleche.com.interfaces.LoginAction;
import youleche.com.model.MRentVehicleInfo;
import youleche.com.util.AESEncryptAndDecrypt;
import youleche.com.util.JsonHelper;
import youleche.com.util.StaticUtil;

/**
 * Servlet implementation class SRentVehicleInfoServlet
 */
public class SRentVehicleInfoServlet extends UlecheHttpServlet {
	private static final long serialVersionUID = 1L;

	public SRentVehicleInfoServlet(){
		super();
	}
	
	/**
	 * freemark静态化配置类
	 */
	 private Configuration cfg = null;
	 
	 @Override
     public void init() throws ServletException
     {
        cfg = new Configuration();
        cfg.setServletContextForTemplateLoading(this.getServletContext(), null);
     }
	 
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int action = Integer.parseInt(request.getParameter("action"));
		switch(action){
			case 0:
				this.releaseRentInfo(request, response);
				break;
			case 1:
				this.getRentInfoById(request, response);
				break;
			case 2:
				//得到列表总条数
				this.getCount(request, response);
				break;
			case 3: 
				//得到列表
				this.getList(request, response);
			case 4: 
				//根据租车ID更新访问量
				this.updateA4(request, response);
				break;
		}
	}
	
	/**
	 * 根据租车ID更新访问量
	 * @param request 请求
	 * @param response 响应
	 */
	private void updateA4(HttpServletRequest request, HttpServletResponse response){		
		String rentId = request.getParameter("id");
		BRentVehicleInfo handler = new BRentVehicleInfo();
		try {
			MRentVehicleInfo rentInfo = handler.getRentVehicleInfoById(rentId);
			handler.updateA4ById(rentId, rentInfo.getA4() + 1);
		} catch (Exception e) {
			//MLLogFactory.exceptionLog("更新租车访问量失败", "更新租车访问量失败", e.getMessage(), request.getRemoteAddr());
		}
	}
	
	/**
	 * 根据用户名得到租车信息总条数
	 * @param request 请求
	 * @param response 响应
	 */
	private void getCount(HttpServletRequest request, HttpServletResponse response){		
		BRentVehicleInfo handler = new BRentVehicleInfo();
		try {
			int count = handler.getRentInfoCount();
			super.response(response, ""+count+"");
		} catch (Exception e) {
			super.response(response, "0");
		}
	}
	
	/**
	 * 租车信息列表
	 * @param request 请求
	 * @param response 响应
	 */
	private void getList(HttpServletRequest request, HttpServletResponse response){		
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		Integer startIndex = (Integer.parseInt(request.getParameter("pageIndex")) - 1) * pageSize ;
		String sortArgs = request.getParameter("sortArgs");
		if("".equals(sortArgs)){
			sortArgs = " addTime desc ";
		}
		String orderBy = "order by " + sortArgs;
		BRentVehicleInfo handler = new BRentVehicleInfo();
		try {
			List<MRentVehicleInfo> list = handler.getRentVehicleInfoForList(startIndex.toString(), ((Integer)pageSize).toString(), orderBy);

			
			JsonHelper.printListToJsonString(response, list);
		} catch (Exception e) {
			super.response(response, "");
		}
	}
	
	/**
	 * 得到租车信息
	 * @param request
	 * @param response
	 */
	private void getRentInfoById(HttpServletRequest request, HttpServletResponse response){
		BRentVehicleInfo handler = new BRentVehicleInfo();
		
		try {
			MRentVehicleInfo rentInfo = handler.getRentVehicleInfoById(request.getParameter("id"));
			MLLogFactory.accLog("租车时间转换为字符串", "租车时间转换为字符串", rentInfo.getAddTime().toString(), "127.0.0.1");
			MRentVehicleInfo preInfo = handler.getPreVehicleInfo(rentInfo.getAddTime().toString());
			MRentVehicleInfo nextInfo = handler.getNextVehicleInfo(rentInfo.getAddTime().toString());
			if(preInfo == null){
				preInfo = rentInfo;
			}
			
			if(nextInfo == null){
				nextInfo = rentInfo;
			}
			request.setAttribute("preInfo", preInfo);
			request.setAttribute("nextInfo", nextInfo);
			request.setAttribute("rentInfo", rentInfo);
			request.getRequestDispatcher("/zcdetail.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发布租车信息
	 * @param request 请求
	 * @param response 响应
	 */
	private void releaseRentInfo(HttpServletRequest request, HttpServletResponse response){
		try{
			LoginAction action = new LoginAction();
			if(action.isLoginToInner(request, response) == "true"){
				MRentVehicleInfo rentVehicleInfo = (MRentVehicleInfo) JsonHelper.getObjectByJsonStringAndGson(request, MRentVehicleInfo.class);
				
				BRentVehicleInfo handler = new BRentVehicleInfo();
				if(handler.getRentVehicleInfoById(rentVehicleInfo.getRentId()) != null){
					return;
				}
				
				String todayCount = handler.getRentVehicleInfoByUserTodayNums(rentVehicleInfo.getReleaseId());
				if(todayCount == null || "".equals(todayCount)){
					todayCount = "0";
				}
				
				int todayCountInt = Integer.parseInt(todayCount);
				if(todayCountInt > 3){
					super.response(response, "3"); //用户今天已经发布超过3条信息了
					return;
				}
				
				ParamConfigParameters paramConfig = new ParamConfigParameters();
				String key = paramConfig.getParameter("LinkNum_KEY");
				rentVehicleInfo.setLinkPhone(AESEncryptAndDecrypt.encrypt(rentVehicleInfo.getLinkPhone(), key));
				rentVehicleInfo.setImageId("0");
				rentVehicleInfo.setIsDelete("0");
				
				BUser uhandler = new BUser();
				rentVehicleInfo.setA3(uhandler.getUserById(rentVehicleInfo.getReleaseId()).getUserName());
				if(handler.addRentVehicleInfo(rentVehicleInfo) > 0){
					StaticUtil.staticRecommendRentInfo(cfg, request, response);
					super.response(response, "1");
					return;
				}else{
					super.response(response, "0");	
					return;
				}
			}else{
				//没登陆返回2
				super.response(response, "2");	
				return;
			}
		}catch(Exception e){
			e.printStackTrace();
			super.response(response, "0");
			MLLogFactory.exceptionLog("用户发布租车信息出错", "用户发布租车信息出错", e.getMessage(), request.getRemoteAddr());
			return;
		}
	}

}
